package org.fuxia.im.listeners;

import java.awt.Component;

import javax.swing.SwingUtilities;

import org.fuxia.im.common.ClientConst;
import org.fuxia.im.common.ClientContext;
import org.fuxia.im.core.entries.ECResponse;
import org.fuxia.im.core.listeners.Listener;
import org.fuxia.im.entities.User;
import org.fuxia.im.gui.AddFriend;
import org.fuxia.im.gui.AddFriendNext;
import org.fuxia.im.gui.Main;

import com.alibaba.fastjson.JSONArray;

public class AddUserFriendsListener implements Listener{

	public void trigger(Object param) {
		
		final ECResponse resp = (ECResponse)param ;
		SwingUtilities.invokeLater(new Runnable() {
			
			public void run() {
				AddFriend add = (AddFriend)ClientContext.getContext().get("addFriend");
				if(resp.getStatusCode() != null || resp.getStatusCode() == 200) {
					handlerSuccess(resp, add) ;
					add.dispose() ;
				}				
			}
		});
	}
	
	public void handlerSuccess(ECResponse resp, Component current){
		Main main = ClientContext.getValue(ClientConst.MAIN_WINDOW, Main.class) ;
		AddFriend frame = (AddFriend)current ;
		int x = frame.getX() ;
		int y = frame.getY() ;
		int width = frame.getWidth() ;
		int height = frame.getHeight() ;
		int flog = 1 ;
		JSONArray user = (JSONArray)resp.get("user") ;
		ClientContext.addUserToGroup(resp.get("groupKey").toString(), user) ;
		main.addFriend(resp.get("groupKey").toString(), user , resp.get("remark").toString()) ;
		Object age = user.get(5) ;
		if(age == null) {
			age = "0" ;
		}
		//String hql = "select user.userCode,user.nickName,user.personNote,user.userState,"
	//	+ "user.imagePath,user.age,user.address,user.sex "
	//	+ "from IMUser user where "
	//	+ " user.userCode=?" ;
		//String hql = "select imagePath,nickName,userCode,sex,age,address from IMUser where userCode=?" ;
		String[] temp = {user.get(4)==null?"images/default.jpg":user.get(4).toString(), 
				user.get(1)==null?"":user.get(1).toString(), user.get(0).toString(), 
						user.get(7)==null?"男":user.get(7).toString(), age.toString()} ;
		
		AddFriendNext next = new AddFriendNext(width, height, x, y, resp.getResponseText().toString(),flog, temp) ;
		next.setVisible(true) ;
	}
}
